package com.kan.awaits.mongo.meta;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBRef;

public class DBObjectTransformer
{
	public static DBObject toDbObject(Object entity, CollectionMeta entityMeta)
	{
		DBObject dObject = new BasicDBObject();
		
		return null;
	}

	public static Object getRefEntity(CollectionMeta entityMeta, DBRef dbRef)
	{
		Class<?> type = entityMeta.getEntityType();
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(type);

		enhancer.setCallback(new MethodInterceptorImpl(dbRef));

		Object my = enhancer.create();

		try
		{
			Field idField = type.getField("id");
			idField.setAccessible(true);
			idField.set(my, dbRef.getId());

		} catch (SecurityException e)
		{
			e.printStackTrace();
		} catch (NoSuchFieldException e)
		{
			e.printStackTrace();
		} catch (IllegalArgumentException e)
		{
			e.printStackTrace();
		} catch (IllegalAccessException e)
		{
			e.printStackTrace();
		}
		return my;
	}

	public static void injectP(Object entity, DBObject dbObject)
	{

	}

	private static class MethodInterceptorImpl implements MethodInterceptor
	{
		DBRef dbRef;

		public MethodInterceptorImpl(DBRef dbRef)
		{
			this.dbRef = dbRef;
		}

		public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable
		{
			System.out.println(method);

			DBObject dbObject = dbRef.fetch();

			DBObjectTransformer.injectP(obj, dbObject);
			// put pro to obj
			proxy.invokeSuper(obj, args);
			return null;
		}
	}
}
